<template>
    <div class="user-manage">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="iconfont icon-yonghu"></i>&nbsp;用户管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-input v-model="query.userName" placeholder="用户名称" class="handle-input mr10" clearable @change="handleSearch"></el-input>
                <el-input v-model="query.userTel" placeholder="用户电话" class="handle-input mr10" clearable @change="handleSearch"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
                <el-button
                        type="primary"
                        icon="el-icon-delete"
                        class="handle-del mr10"
                        @click="delAllSelection"
                >批量删除</el-button>
            </div>
            <el-table
                    :data="tableData"
                    border
                    class="table"
                    ref="multipleTable"
                    :height="tableHeight"
                    header-cell-class-name="table-header"
                    @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" align="center"></el-table-column>
                <el-table-column type="index" label="序号" width="55" align="center" :index='(index)=>{return (index+1) + (query.currentPage-1)*query.pageSize }'></el-table-column>
                <el-table-column prop="userName" label="用户姓名" align="center"></el-table-column>
                <el-table-column label="用户角色" align="center">
                    <template slot-scope="scope">
                        <span>{{ scope.row.role==2?'家属':'管理员' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="登陆账号" align="center">
                    <template slot-scope="scope">
                        <span><i class="iconfont icon-zhanghao" style="font-size: 14px;color: #409eff"></i> {{ scope.row.loginName }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="loginPassword" label="用户密码" align="center">
                    <template slot-scope="scope">
                        <span v-if="!scope.row.isWatch" style="vertical-align: middle;position: relative;top:3px">******</span>
                        <span v-if="scope.row.isWatch" style="vertical-align: middle">{{ scope.row.loginPassword }}</span>
                        &nbsp;&nbsp;<i class="el-icon-view" style="vertical-align: middle;cursor: pointer" :style="`color:${scope.row.isWatch?'#409eff':''}`" @click="scope.row.isWatch = !scope.row.isWatch"></i>
                    </template>
                </el-table-column>
                <el-table-column prop="userSex" label="性别" align="center">
                    <template slot-scope="scope">
                        <span v-if="scope.row.userSex == '男'">
                            <el-tooltip class="item" effect="dark" content="男" placement="top">
                                <i class="iconfont icon-male" style="font-size: 14px;color: #409eff"></i>
                            </el-tooltip>
                        </span>
                        <span v-if="scope.row.userSex == '女'">
                            <el-tooltip class="item" effect="dark" content="女" placement="top">
                                <i class="iconfont icon-nv" style="color: #FF8CFD"></i>
                            </el-tooltip>
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="userTel" label="用户电话" align="center"></el-table-column>
                <el-table-column prop="cardId" label="身份证号" align="center"></el-table-column>

                <el-table-column label="操作" width="150" align="center">
                    <template slot-scope="scope">
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="handleEdit(scope.$index, scope.row)"
                        >修改</el-button>
                        <el-button
                                type="text"
                                icon="el-icon-delete"
                                @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                        background
                        layout="-> ,sizes , prev, pager, next"
                        :current-page="query.currentPage"
                        :page-size="query.pageSize"
                        :total="pageTotal"
                        @current-change="handlePageChange"
                        @size-change="handleSizeChange"
                        :page-sizes="[10, 20, 50, 100]"
                ></el-pagination>
            </div>
        </div>

        <!-- 新增/编辑弹出框 -->
        <el-dialog :title="dialogTitle" v-dialogDrag :visible.sync="editVisible" width="555px">
            <el-form ref="form" :model="form" label-position="left" label-width="90px" :rules="rules">
                <el-form-item label="登录名" prop="loginName">
                    <el-input v-model="form.loginName" maxlength="11" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="登录密码" prop="loginPassword">
                    <el-input v-model="form.loginPassword" maxlength="11" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="用户角色" prop="role">
                    <el-radio v-model="form.role" :label="1" disabled>管理员</el-radio>
                    <el-radio v-model="form.role" :label="2">家属</el-radio>
                </el-form-item>
                <el-form-item label="用户姓名" prop="userName">
                    <el-input v-model="form.userName"></el-input>
                </el-form-item>
                <el-form-item label="用户性别" prop="userSex">
                    <el-radio v-model="form.userSex" label="男">男</el-radio>
                    <el-radio v-model="form.userSex" label="女">女</el-radio>
                </el-form-item>
                <el-form-item label="用户电话" prop="userTel">
                    <el-input type="text" v-model="form.userTel" maxlength="11" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="身份证号" prop="cardId">
                    <el-input type="text" v-model="form.cardId" maxlength="18" show-word-limit></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="saveEdit">确 定</el-button>
                <el-button @click="editVisible = false">取 消</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import { fetchData } from '../../api/index';
    export default {
        data() {

            var loginName = (rule, value, callback) => {
                const reg = /^[a-z0-9]+$/i;
                if (!reg.test(value)) {
                    return callback(new Error('登录名不能含有中文、特殊字符'));
                } else {
                    callback();
                }
            };

            var loginPassword = (rule, value, callback) => {
                const reg = /^[a-z0-9]+$/i;
                if (!reg.test(value)) {
                    return callback(new Error('登录密码不能含有中文、特殊字符'));
                } else {
                    callback();
                }
            };

            var userName = (rule, value, callback) => {
                const reg = /^[a-z0-9]+$/i;
                if (!reg.test(value)) {
                    return callback(new Error('用户姓名不能含有中文、特殊字符'));
                } else {
                    callback();
                }
            };

            var userTel = (rule, value, callback) => {
                const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
                if (!reg.test(value)) {
                    return callback(new Error('用户电话格式错误'));
                } else {
                    callback();
                }
            };

            var cardId = (rule, value, callback) => {
                const reg = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
                if (!reg.test(value)) {
                    return callback(new Error('身份证号格式错误'));
                } else {
                    callback();
                }
            };

            return {
                query               : {
                                          userName    : '',
                                          userTel     : '',
                                          currentPage : 1,
                                          pageSize    : 10
                                      },
                tableData           : [],
                multipleSelection   : [],
                delList             : [],
                editVisible         : false,
                pageTotal           : 0,
                dialogTitle         : '',
                form                : {
                                          loginName : '',
                                          loginPassword : '',
                                          role : 2,
                                          userName : '',
                                          userSex : '男',
                                          userTel : '',
                                          cardId : '',
                                      },
                tableHeight         : document.documentElement.clientHeight-350,    // 表格高度
                rules               : {
                                          loginName       : [{ required: true, validator: loginName, trigger: 'blur' }],
                                          loginPassword   : [{ required: true, validator: loginPassword, trigger: 'blur' }],
                                          role            : [{ required: true}],
                                          userName        : [{ required: true, validator: userName, trigger: 'blur' }],
                                          userSex         : [{ required: true}],
                                          userTel         : [{ required: true, validator: userTel, trigger: 'blur' }],
                                          cardId          : [{ required: true, validator: cardId, trigger: 'blur' }],
                                      },
            };
        },
        watch :{
            /**
             * 监听新增/编辑 弹窗关闭 重置表单数据
             * @param   nv 新值
             * @param   ov 之前值
             */
            editVisible(nv,ov){
                if(!nv){
                    // 重置表单数据
                    this.$refs.form.resetFields();

                    /**
                     * 由于from点id未被表单绑定，当表单清空时，id不能及时清空，需要手动清除
                     */
                    if(this.form.id){
                        delete this.form.id;
                    };
                }
            },
        },
        methods: {
            /**
             * 获取表格数据
             */
            getData() {
                this.$api.getUsers(this.query).then((res)=>{

                    for(var i=0;i<res.data.length;i++){
                        res.data[i].isWatch = false;
                    };

                    this.tableData = res.data;
                    this.pageTotal = res.total;
                })
            },

            /**
             * 触发搜索按钮
             */
            handleSearch() {
                this.$set(this.query, 'currentPage', 1);
                this.getData();
            },

            /**
             * 删除操作
             */
            handleDelete(index, row) {
                // 二次确认删除
                this.$confirm(`确定要删除 ${row.userName} 用户的账号吗？`, '提示', {
                    type: 'warning',
                    center: true
                }).then(() => {
                        this.$api.deleteUser([
                            row.id
                        ]).then((res)=>{
                            this.$message.success('删除成功');
                            this.getData();
                        })
                }).catch(() => {});
            },

            /**
             * 多选操作
             */
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },

            /**
             * 删除选中数据
             */
            delAllSelection() {
                let length = this.multipleSelection.length,
                    arr    = [];

                // 没有选择项直接结束
                if (!length) return;

                for (let i = 0; i < length; i++) {
                    arr.push(this.multipleSelection[i].id);
                };

                this.$api.deleteUser(arr).then((res)=>{
                    this.$message.success('删除成功');
                    this.multipleSelection = [];
                    this.getData();
                })

            },

            /**
             * 新增操作
             */
            handleAdd(){
                this.dialogTitle = "新增用户信息";
                this.editVisible = true;
            },

            /**
             * 编辑操作
             */
            handleEdit(index, row) {
                this.dialogTitle = "编辑用户信息";
                this.editVisible = true;

                // this.$nextTick()将赋值操作放到dom渲染结束之后
                this.$nextTick(() => {
                    this.form = JSON.parse(JSON.stringify(row));
                })
            },

            /**
             * 保存编辑
             */
            saveEdit() {
                this.$refs.form.validate(valid => {
                    if (!valid) {
                        return this.$message({
                            message: '请核对填写信息',
                            type: 'error'
                        });
                    };

                    this.$api.updateUser(this.form).then((res)=>{
                        if( this.form.id ){
                            this.$message.success("修改用户信息成功");
                        }else {
                            this.$message.success("新增用户信息成功");
                        };
                        this.editVisible = false;
                        this.handleSearch();
                    });
                });

            },

            /**
             * 分页导航 改变展示页
             */
            handlePageChange(val) {
                this.$set(this.query, 'currentPage', val);
                this.getData();
            },

            /**
             * 分页导航 改变展示数量
             * @param index
             */
            handleSizeChange(index) {
                this.$set(this.query, 'pageSize', index);
                this.getData();
            },

        },
        beforeMount() {
            this.getData();
        }
    };
</script>

<style lang="less">

</style>
